<template>
  <div class="archive-info-tab">
    <!-- 档案基本信息 -->
    <a-row :gutter="24" class="basic-info-section">
      <a-col :span="24">
        <a-card title="档案基本信息" size="small">
          <a-descriptions :column="2" bordered>
            <a-descriptions-item label="档案号">
              <a-tag color="blue">{{ archive.id }}</a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="档案状态">
              <a-tag :color="archive.status === 'alive' ? 'green' : 'red'">
                {{ archive.status === 'alive' ? '在世' : '已故' }}
              </a-tag>
            </a-descriptions-item>
            <a-descriptions-item label="创建时间">
              {{ formatDate(archive.lastUpdated) }}
            </a-descriptions-item>
            <a-descriptions-item label="创建人员">
              {{ archive.createdBy || '系统' }}
            </a-descriptions-item>
            <a-descriptions-item label="最后更新">
              {{ formatDate(archive.lastUpdated) }}
            </a-descriptions-item>
            <a-descriptions-item label="数据完整性">
              <a-progress :percent="getDataCompletion()" :stroke-color="getCompletionColor(getDataCompletion())" size="small" />
            </a-descriptions-item>
            <a-descriptions-item label="档案标签" :span="2">
              <a-space wrap>
                <a-tag v-for="tag in archive.tags || []" :key="tag" :color="getTagColor(tag)">
                  {{ tag }}
                </a-tag>
              </a-space>
            </a-descriptions-item>
          </a-descriptions>
        </a-card>
      </a-col>
    </a-row>

    <!-- 生命数据统计 -->
    <a-row :gutter="24" class="stats-section">
      <a-col :span="12">
        <a-card title="生命数据统计" size="small">
          <div class="life-stats">
            <div class="stat-item">
              <span class="label">当前年龄：</span>
              <span class="value">{{ archive.age }}岁</span>
            </div>
            <div class="stat-item">
              <span class="label">预定寿命：</span>
              <span class="value">{{ archive.lifespan }}岁</span>
            </div>
            <div class="stat-item">
              <span class="label">生命进度：</span>
              <a-progress :percent="getLifeProgress()" :stroke-color="getLifeProgressColor()" size="small" />
            </div>
            <div class="stat-item">
              <span class="label">业力值：</span>
              <span class="value" :style="{ color: getKarmaColor(archive.karma) }">
                {{ archive.karma }}
              </span>
            </div>
            <div class="stat-item">
              <span class="label">生命事件数：</span>
              <span class="value">{{ getMajorEventsCount() }}件</span>
            </div>
          </div>
        </a-card>
      </a-col>

      <a-col :span="12">
        <a-card title="社会关系统计" size="small">
          <div class="social-stats">
            <div class="stat-item">
              <span class="label">家庭成员：</span>
              <span class="value">{{ getFamilyMembersCount() }}人</span>
            </div>
            <div class="stat-item">
              <span class="label">朋友圈子：</span>
              <span class="value">{{ getFriendsCount() }}人</span>
            </div>
            <div class="stat-item">
              <span class="label">师承关系：</span>
              <span class="value">{{ getMentorsCount() }}人</span>
            </div>
            <div class="stat-item">
              <span class="label">社交组织：</span>
              <span class="value">{{ getSocialCirclesCount() }}个</span>
            </div>
            <div class="stat-item">
              <span class="label">仇敌记录：</span>
              <span class="value" style="color: #f5222d">{{ getEnemiesCount() }}个</span>
            </div>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 档案操作记录 -->
    <a-row :gutter="24" class="operations-section">
      <a-col :span="24">
        <a-card title="档案操作记录" size="small">
          <a-timeline>
            <a-timeline-item v-for="record in getOperationRecords()" :key="record.id" :color="getOperationColor(record.type)">
              <template #dot>
                <component :is="getOperationIcon(record.type)" style="font-size: 14px" />
              </template>
              <div class="operation-content">
                <h4>{{ record.title }}</h4>
                <p>{{ record.description }}</p>
                <div class="operation-meta">
                  <span>操作人：{{ record.operator }}</span>
                  <span>时间：{{ formatDate(record.timestamp) }}</span>
                </div>
              </div>
            </a-timeline-item>
          </a-timeline>
        </a-card>
      </a-col>
    </a-row>

    <!-- 数据质量评估 -->
    <a-row :gutter="24" class="quality-section">
      <a-col :span="24">
        <a-card title="数据质量评估" size="small">
          <div class="quality-assessment">
            <a-row :gutter="16">
              <a-col :span="8">
                <div class="quality-item">
                  <h4>基础信息完整度</h4>
                  <a-progress :percent="getBasicInfoCompletion()" :stroke-color="getCompletionColor(getBasicInfoCompletion())" />
                  <p class="quality-desc">{{ getBasicInfoCompletion() }}% 完整</p>
                </div>
              </a-col>
              <a-col :span="8">
                <div class="quality-item">
                  <h4>生命历程丰富度</h4>
                  <a-progress :percent="getLifeHistoryRichness()" :stroke-color="getCompletionColor(getLifeHistoryRichness())" />
                  <p class="quality-desc">{{ getLifeHistoryRichness() }}% 丰富</p>
                </div>
              </a-col>
              <a-col :span="8">
                <div class="quality-item">
                  <h4>关系网络密度</h4>
                  <a-progress :percent="getSocialNetworkDensity()" :stroke-color="getCompletionColor(getSocialNetworkDensity())" />
                  <p class="quality-desc">{{ getSocialNetworkDensity() }}% 密度</p>
                </div>
              </a-col>
            </a-row>

            <a-divider />

            <div class="quality-summary">
              <h4>档案质量总结</h4>
              <a-alert :message="getQualityMessage()" :description="getQualityDescription()" :type="getQualityType()" show-icon />
            </div>
          </div>
        </a-card>
      </a-col>
    </a-row>

    <!-- 导出选项 -->
    <a-row :gutter="24" class="export-section">
      <a-col :span="24">
        <a-card title="档案导出" size="small">
          <div class="export-options">
            <a-space size="large">
              <a-button type="primary" @click="exportArchive('pdf')">
                <FilePdfOutlined />
                导出PDF
              </a-button>
              <a-button @click="exportArchive('excel')">
                <FileExcelOutlined />
                导出Excel
              </a-button>
              <a-button @click="exportArchive('json')">
                <FileTextOutlined />
                导出JSON
              </a-button>
              <a-button @click="printArchive()">
                <PrinterOutlined />
                打印档案
              </a-button>
            </a-space>
          </div>
        </a-card>
      </a-col>
    </a-row>
  </div>
</template>

<script setup>
import { computed } from 'vue'
import { message } from 'ant-design-vue'
import { FilePdfOutlined, FileExcelOutlined, FileTextOutlined, PrinterOutlined, PlusOutlined, EditOutlined, DeleteOutlined, UserOutlined, ClockCircleOutlined } from '@ant-design/icons-vue'
import dayjs from 'dayjs'

// 组件属性
const props = defineProps({
  archive: {
    type: Object,
    required: true
  }
})

// 计算属性
const getDataCompletion = () => {
  let score = 0
  let total = 0

  // 基础信息完整度
  const basicInfo = props.archive.basicInfo || {}
  const basicFields = ['fullName', 'idCard', 'birthPlace', 'profession']
  basicFields.forEach((field) => {
    total += 1
    if (basicInfo[field]) score += 1
  })

  // 生命历程丰富度
  const lifeHistory = props.archive.lifeHistory || {}
  total += 2
  if (lifeHistory.birthDate) score += 1
  if (lifeHistory.majorEvents && lifeHistory.majorEvents.length > 0) score += 1

  // 社会关系完整度
  const socialNetwork = props.archive.socialNetwork || {}
  total += 3
  if (socialNetwork.family) score += 1
  if (socialNetwork.friends && socialNetwork.friends.length > 0) score += 1
  if (socialNetwork.socialCircles && socialNetwork.socialCircles.length > 0) score += 1

  return Math.round((score / total) * 100)
}

const getLifeProgress = () => {
  return Math.round((props.archive.age / props.archive.lifespan) * 100)
}

const getLifeProgressColor = () => {
  const progress = getLifeProgress()
  if (progress < 50) return '#52c41a'
  if (progress < 80) return '#faad14'
  return '#f5222d'
}

const getKarmaColor = (karma) => {
  if (karma >= 80) return '#52c41a'
  if (karma >= 40) return '#1890ff'
  if (karma >= 0) return '#faad14'
  if (karma >= -40) return '#fa541c'
  return '#f5222d'
}

const getCompletionColor = (percent) => {
  if (percent >= 80) return '#52c41a'
  if (percent >= 60) return '#1890ff'
  if (percent >= 40) return '#faad14'
  return '#f5222d'
}

const getTagColor = (tag) => {
  const colors = {
    正常档案: 'green',
    信息完整: 'blue',
    重点关注: 'orange',
    业力异常: 'red',
    新建档案: 'purple'
  }
  return colors[tag] || 'default'
}

// 统计方法
const getMajorEventsCount = () => {
  return props.archive.lifeHistory?.majorEvents?.length || 0
}

const getFamilyMembersCount = () => {
  const family = props.archive.socialNetwork?.family || {}
  const parents = family.parents?.length || 0
  const spouse = family.spouse ? 1 : 0
  const children = family.children?.length || 0
  const siblings = family.siblings?.length || 0
  return parents + spouse + children + siblings
}

const getFriendsCount = () => {
  return props.archive.socialNetwork?.friends?.length || 0
}

const getMentorsCount = () => {
  return props.archive.socialNetwork?.mentors?.length || 0
}

const getSocialCirclesCount = () => {
  return props.archive.socialNetwork?.socialCircles?.length || 0
}

const getEnemiesCount = () => {
  return props.archive.socialNetwork?.enemies?.length || 0
}

// 质量评估方法
const getBasicInfoCompletion = () => {
  const basicInfo = props.archive.basicInfo || {}
  const requiredFields = ['fullName', 'idCard', 'birthPlace', 'profession', 'nationality']
  const completedFields = requiredFields.filter((field) => basicInfo[field])
  return Math.round((completedFields.length / requiredFields.length) * 100)
}

const getLifeHistoryRichness = () => {
  const lifeHistory = props.archive.lifeHistory || {}
  let score = 0

  if (lifeHistory.birthDate) score += 20
  if (lifeHistory.majorEvents && lifeHistory.majorEvents.length > 0) score += 30
  if (lifeHistory.growthTrack && lifeHistory.growthTrack.length > 0) score += 25
  if (lifeHistory.achievements && lifeHistory.achievements.length > 0) score += 25

  return Math.min(score, 100)
}

const getSocialNetworkDensity = () => {
  const socialNetwork = props.archive.socialNetwork || {}
  let score = 0

  if (socialNetwork.family) score += 30
  if (socialNetwork.friends && socialNetwork.friends.length > 0) score += 25
  if (socialNetwork.mentors && socialNetwork.mentors.length > 0) score += 20
  if (socialNetwork.socialCircles && socialNetwork.socialCircles.length > 0) score += 25

  return Math.min(score, 100)
}

const getQualityMessage = () => {
  const completion = getDataCompletion()
  if (completion >= 90) return '档案质量优秀'
  if (completion >= 70) return '档案质量良好'
  if (completion >= 50) return '档案质量一般'
  return '档案质量较差'
}

const getQualityDescription = () => {
  const completion = getDataCompletion()
  if (completion >= 90) return '档案信息非常完整，数据质量优秀，可以进行各种业务操作。'
  if (completion >= 70) return '档案信息比较完整，建议补充部分缺失信息以提高数据质量。'
  if (completion >= 50) return '档案信息存在较多缺失，建议尽快补充完善。'
  return '档案信息严重不完整，请及时补充必要信息。'
}

const getQualityType = () => {
  const completion = getDataCompletion()
  if (completion >= 90) return 'success'
  if (completion >= 70) return 'info'
  if (completion >= 50) return 'warning'
  return 'error'
}

// 操作记录
const getOperationRecords = () => {
  return [
    {
      id: 1,
      type: 'create',
      title: '档案创建',
      description: '档案首次创建，录入基础信息',
      operator: props.archive.createdBy || '系统',
      timestamp: props.archive.lastUpdated
    },
    {
      id: 2,
      type: 'update',
      title: '信息更新',
      description: '更新了基础信息和生命历程数据',
      operator: '地府文书',
      timestamp: props.archive.lastUpdated
    },
    {
      id: 3,
      type: 'view',
      title: '档案查看',
      description: '档案被查看和审核',
      operator: '当前用户',
      timestamp: new Date().toISOString()
    }
  ]
}

const getOperationColor = (type) => {
  const colors = {
    create: 'green',
    update: 'blue',
    delete: 'red',
    view: 'gray'
  }
  return colors[type] || 'gray'
}

const getOperationIcon = (type) => {
  const icons = {
    create: PlusOutlined,
    update: EditOutlined,
    delete: DeleteOutlined,
    view: UserOutlined
  }
  return icons[type] || ClockCircleOutlined
}

// 工具方法
const formatDate = (dateString) => {
  if (!dateString) return '未知'
  return dayjs(dateString).format('YYYY-MM-DD HH:mm:ss')
}

// 导出方法
const exportArchive = (format) => {
  message.success(`正在导出${format.toUpperCase()}格式档案...`)
}

const printArchive = () => {
  message.success('正在准备打印档案...')
}
</script>

<style lang="scss" scoped>
@use '@/styles/variables.scss' as *;

.archive-info-tab {
  .basic-info-section,
  .stats-section,
  .operations-section,
  .quality-section,
  .export-section {
    margin-bottom: $spacing-lg;
  }

  .stats-section {
    .life-stats,
    .social-stats {
      .stat-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: $spacing-sm 0;
        border-bottom: 1px solid #f0f0f0;

        &:last-child {
          border-bottom: none;
        }

        .label {
          font-weight: 500;
          color: #666;
        }

        .value {
          font-weight: 500;
          color: #1890ff;
        }
      }
    }
  }

  .operations-section {
    .operation-content {
      h4 {
        margin: 0 0 $spacing-xs 0;
        color: #1890ff;
        font-size: 14px;
      }

      p {
        margin: 0 0 $spacing-xs 0;
        color: #666;
        font-size: 12px;
      }

      .operation-meta {
        display: flex;
        gap: $spacing-md;
        font-size: 12px;
        color: #999;
      }
    }
  }

  .quality-section {
    .quality-assessment {
      .quality-item {
        text-align: center;

        h4 {
          margin-bottom: $spacing-md;
          color: #1890ff;
          font-size: 14px;
        }

        .quality-desc {
          margin-top: $spacing-sm;
          font-size: 12px;
          color: #666;
        }
      }

      .quality-summary {
        h4 {
          color: #1890ff;
          margin-bottom: $spacing-md;
        }
      }
    }
  }

  .export-section {
    .export-options {
      text-align: center;
      padding: $spacing-lg;
      background: #fafafa;
      border-radius: 8px;
    }
  }
}

// 响应式样式
@media (max-width: 768px) {
  .archive-info-tab {
    .stats-section {
      .ant-col {
        margin-bottom: $spacing-md;
      }
    }

    .quality-assessment {
      .ant-col {
        margin-bottom: $spacing-md;
      }
    }
  }
}
</style>
